#include "stack.h"
int stack_init(my_stack *st){
    if(!st) return -1;
    memset(st, 0, sizeof(my_stack));
    return 0;
}

int stack_push(my_stack *st, int val){
    if(!st) return -1;

    node_t *node = (node_t *)malloc(sizeof(node_t));
    if(!node) return -1;

    node->pFront = NULL;
    node->id = val;
    node->pNext = st->stack_top;

    if(st->stack_top){
        st->stack_top->pFront = node;
    }

    st->stack_top = node;
    st->stack_size++;
    return 0;
}

int stack_pop(my_stack *st){
    if(!st || st->stack_size == 0) return -1;

    node_t *tmp = st->stack_top;
    st->stack_top = st->stack_top->pNext;

    if(st->stack_top){
        st->stack_top->pFront = NULL;
    }

    free(tmp);
    --st->stack_size;
    return 0; // 注意这里返回结果代表出栈正确与否，与出栈的元素无关
}

void print_stack(my_stack st){
    node_t *tmp = st.stack_top; 
    while(tmp){
        printf("%d ", tmp->id);
        tmp = tmp->pNext;
    }
    printf("\n");
}

int stack_destroy(my_stack *st){
    if(!st) return -1;

    while(st->stack_size){
        stack_pop(st);
    }
    st->stack_top = NULL;
    st->stack_size = 0;
    return 0;
}

int stack_copy(my_stack *dest, my_stack *src){
    if (!src || !dest) return -1;
    if (src->stack_size == 0) {
        return 0; // 空栈直接返回
    }

    // 1、数组临时存储栈元素
    int *tmpArr = (int*)calloc(src->stack_size, sizeof(int));

    // 2、源栈元素存入数组
    node_t *tmp = src->stack_top;
    for(int i = 0; i < src->stack_size; i++){
        tmpArr[i] = tmp->id;
        tmp = tmp->pNext;
    }

    // 3、数组中元素存入目标栈
    for(int i = src->stack_size - 1; i >= 0; i--){
        stack_push(dest, tmpArr[i]);
    }

    free(tmpArr);

    return 0;
}
